import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../leak/model/leak_info.dart';
import '../leak/model/leak_node.dart';
import '../task/local_save_leak.dart';
import '../utils/log_util.dart';
import 'leak_widget.dart';

class AllLeakPage extends StatefulWidget {
  const AllLeakPage({Key? key}) : super(key: key);

  static void openAllLeakPage(BuildContext context) {
    Navigator.maybeOf(context)?.push(CupertinoModalPopupRoute(
      builder: (context) {
        return const AllLeakPage();
      },
    ));
  }

  @override
  State<StatefulWidget> createState() => AllLeakPageState();
}

class AllLeakPageState extends State<AllLeakPage> with TickerProviderStateMixin {
  TabController? _tabController;
  final List<String> _tabsTitle = [];
  int _currentTabIndex = 0;
  LeakInfo? _currentLeakDetail;
  bool _showLeakDetail = false;
  final GlobalKey<LeakWidgetState> _leakWidgetStateKey = GlobalKey<LeakWidgetState>();

  @override
  void initState() {
    _tabsTitle.add("默认排序");
    _tabsTitle.add("最近发生");
    _tabsTitle.add("最多发生");
    _tabsTitle.add("引用链最短");
    _tabsTitle.add("引用链最长");
    _tabController = TabController(length: _tabsTitle.length, vsync: this);

    super.initState();
  }

  void _refresh() {
    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("全部泄露事件"),
        actions: [
          PopupMenuButton(
            itemBuilder: (ctx) {
              return [
                PopupMenuItem(
                  onTap: () {
                    localSavaLeak.printAllLeak();
                  },
                  padding: const EdgeInsets.all(8),
                  child: const Text("打印全部"),
                ),
                PopupMenuItem(
                  onTap: () {
                    localSavaLeak.clearSavedFile();
                  },
                  padding: const EdgeInsets.all(8),
                  child: const Text("清空全部"),
                ),
              ];
            },
            child: Center(
              child: Container(
                margin: const EdgeInsets.only(left: 10, right: 10),
                padding: const EdgeInsets.only(left: 10, right: 10),
                child: const Text("选项"),
              ),
            ), //
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: _tabsTitle.map((e) => Tab(text: e)).toList(growable: false),
          isScrollable: true,
          automaticIndicatorColorAdjustment: true,
          onTap: (value) {
            _currentTabIndex = value;
            _refresh();
          },
        ),
      ),
      body: Column(
        children: [
          Expanded(
              child: Stack(
            children: [
              TabBarView(
                controller: _tabController,
                children: _tabsTitle
                    .map((e) => LeakListWidget(_currentTabIndex, (leakInfo) {
                          _currentLeakDetail = leakInfo;
                          _showLeakDetail = true;
                          _leakWidgetStateKey.currentState?.scroll2top();
                          _refresh();
                        }))
                    .toList(growable: false),
              ),
              Offstage(
                offstage: !_showLeakDetail,
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Flexible(
                      flex: 1,
                      child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        child: const SizedBox.expand(),
                        onTap: () {
                          _showLeakDetail = false;
                          _refresh();
                        },
                      ),
                    ),
                    Flexible(
                      flex: 3,
                      child: Container(
                        color: Colors.grey,
                        child: LeakWidget(
                          toList(_currentLeakDetail?.node),
                          key: _leakWidgetStateKey,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          )),
        ],
      ),
    );
  }

  void closeBottomSheet(BuildContext context) {
    Navigator.maybeOf(context)?.pop();
  }
}

typedef OnLeakItemPressed = void Function(LeakInfo leakInfo);

// 关键字筛选，tbd
class LeakListWidget extends StatefulWidget {
  final int order;
  final OnLeakItemPressed onLeakItemPressed;

  const LeakListWidget(this.order, this.onLeakItemPressed, {Key? key}) : super(key: key);

  @override
  State<LeakListWidget> createState() => _LeakListWidgetState();
}

class _LeakListWidgetState extends State<LeakListWidget> with AutomaticKeepAliveClientMixin {
  LeakList _leakList = LeakList();

  @override
  void initState() {
    _initLeaks();
    super.initState();
  }

  Future<void> _initLeaks() async {
    _leakList = (await localSavaLeak.getAllLeaks()) ?? LeakList();
    _refresh();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListView.builder(
      itemBuilder: (context, index) {
        final item = _leakList.leakInfo?[index];
        return Container(
          margin: const EdgeInsets.only(left: 5, right: 5, top: 10, bottom: 10),
          child: OutlinedButton(
            onPressed: () {
              if (null != item) {
                widget.onLeakItemPressed.call(item);
              }
            },
            child: Container(
              padding: const EdgeInsets.only(top: 10, bottom: 10),
              child: Stack(
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              item?.node?.name ?? "",
                              style: titleTextStyle(),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                            const SizedBox(height: 10),
                            Text(
                              item?.node?.toString() ?? "",
                              maxLines: 3,
                              overflow: TextOverflow.ellipsis,
                              style: descTextStyle(),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(width: 10),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          const SizedBox(height: 12),
                          ElevatedButton(
                            onPressed: () {
                              LogUtil.d(item?.toString());
                              // LogUtil.d(item?.toJson().toString() ?? "");
                            },
                            child: const Text("打印"),
                          ),
                          Text(
                            "次数${item?.occurCount ?? 0}",
                            maxLines: 3,
                            overflow: TextOverflow.ellipsis,
                            style: descTextStyle(),
                          ),
                        ],
                      )
                    ],
                  ),
                  Align(
                    alignment: Alignment.topRight,
                    child: Text(
                      item?.time ?? "",
                      maxLines: 3,
                      overflow: TextOverflow.ellipsis,
                      style: descTextStyle(),
                    ),
                  )
                ],
              ),
            ),
          ),
        );
      },
      itemCount: _leakList.leakInfo?.length ?? 0,
    );
  }

  @override
  bool get wantKeepAlive => true;

  static TextStyle titleTextStyle() {
    return const TextStyle(
      color: Color(0xff333333),
      fontSize: 18,
      fontWeight: FontWeight.w600,
    );
  }

  static TextStyle descTextStyle() {
    return const TextStyle(
      color: Color(0xff999999),
      fontSize: 14,
    );
  }

  void _refresh() {
    if (mounted) setState(() {});
  }
}
